<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="../vue.js"></script>
  <script src="./vue-router.js"></script>
</head>

<body>

  <div id="app">
    <router-link tag="button" to="/position">职位</router-link>
    <router-link tag="button" to="/search">搜索</router-link>
    <router-link tag="button" to="/profile">我的</router-link>
    <router-view></router-view>
  </div>


  <script>

    var position = {
      template: `<div>position</div>`
      // beforeRouteEnter() {

      // }
    }
    var search = { template: `<div>search</div>` }
    var profile = { template: `<div>profile</div>` }

    var routes = [
      {
        path: "/login",
        component: {
          template: '<div>登录页面</div>'
        }
      },
      {
        path: '/position',
        component: position,
        meta: { auth: false }
      },
      {
        path: '/search',
        component: search,
        meta: { auth: false }
      },
      {
        path: '/profile',
        component: profile,
        meta: { auth: true }
      }
    ]

    var router = new VueRouter({
      routes
    })

    router.beforeEach((to, from, next) => {
      console.log(to)
      if (to.meta.auth) {
        if (localStorage.getItem("username")) {
          next()
        } else {
          next({ path: '/login' })
        }
      } else {
        next();
      }


    })


    router.afterEach((to, from) => {
      // ...
      console.log('after each ...')
    })

    var vm = new Vue({
      router
    }).$mount('#app')

  </script>

</body>

</html>